package stackexchange.analyzer;

import static stackexchange.Constants.PROC_OF_USERS;

import java.util.Vector;

import stackexchange.User;
import stackexchange.UserGroup;
import stackexchange.posts.Answer;
import stackexchange.posts.Question;

public class ReachAnalyzer implements ExpertAnalyzer {

	Vector<Question> questions;

	@Override
	public UserGroup analyze(UserGroup userGroup, Vector<Question> questions,
			Vector<Answer> answers) {
		// calculate z-score for all users
		this.questions = questions;
		Vector<User> allUsers = userGroup.getUsers();
		for (int i = 1; i < allUsers.size(); i++) {
			Vector<Answer> answersOfUser = allUsers.get(i).getUsersAnswers();
			Vector<Integer> helpedUsers = new Vector<Integer>();
			for (int j = 0; j < answersOfUser.size(); j++) {
				int k = getHelpedUserId(answersOfUser.get(j).getParentId());
				if (!helpedUsers.contains(k)) {
					helpedUsers.add(k);
				}
			}
			allUsers.get(i).setExpertiseScore(helpedUsers.size());
		}
		// sort
		UserGroup allUsersGroup =
		// return
		new UserGroup(allUsers).sortOnExpertiseScore();
		Vector<User> sortedUsers = allUsersGroup.getUsers();
		// take %? procent of users
		Vector<User> expertUsers = new Vector<User>();
		for (int i = 0; i < allUsers.size() * PROC_OF_USERS; i++) {
			expertUsers.add(sortedUsers.get(i));
		}
		return new UserGroup(expertUsers);
	}

	private int getHelpedUserId(int postId) {
		for (int k = 0; k < questions.size(); k++) {
			if (postId == questions.get(k).getPostId()) {
				return questions.get(k).getOwnedUserId();
			}
		}
		return -1;
	}

}
